<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CateController extends Controller
{   
    //后台商品分类添加页面
   public function getAdd()
   {	
   		// //查询
   		// $cates = DB::table('cate')->get();
   		$cates = DB::table('cate')
    		->select(DB::raw('*,concat(path,",",id) as paths'))
    		->orderBy('paths')
    		->get();
   		//遍历
		foreach ($cates as $k => $v) {
			//获取path路径的长度 
			$arr = explode(',',$v->path);
			//1为顶级类不用加|---- 2个长度为二级类加|---- 3个长度为三级类加两个|----
			$len = count($arr)-1;
			//给name加|----  所有改的是name的值$cates[$k]->name = ....
			$cates[$k]->cname = str_repeat('|----', $len).$v->cname ;
		}
   		// dd($cates);
        //解析模板
   		return view('admin.cate.add',['cates'=>$cates]);
        
   }

   //后台商品分类添加
   public function postInsert(Request $request)
   {
      $this->validate($request, [
          'cname' => 'required',
        ],[
          'cname.required'=>'商品分类名不能为空',
        ]);
   		// dd($request->all());

   		//拼接数据
   		$data = $request->only(['cname','pid']);
   		//判断是否为顶级分类
   		if($data['pid'] == 0){
   			$data['path'] = 0;
   		}else{
   			//pata['pid']不等于0的话属于子分类
   			//先查询父级的path路径
   			$res = DB::table('cate')->where('id',$data['pid'])->first();
   			//拼接路径
   			$data['path'] = $res->path.','.$data['pid'];
   			// dd($data);
	   		}
   		
   			//添加数据
   		   	$ress = DB::table('cate')->insert($data);
   			// dd($ress);

   		   	// 判断
	        if($ress)
	        {
	            return redirect('/admin/cate/index')->with('success','添加成功');
	        }else
	        {
	            return back()->with('error','添加失败');
	        }

   	}


   		//分类列表页
     public function getIndex(Request $request)
    {		
    	//调用递归
    	// $res = self::getCatesBy(0);
    	//调用优化递归
    	// $arr = self::getAllCates();
    	// $res = self::getCatesByArr($arr,0);



   		//查询
   		// $cates = DB::table('cates')->get();
   		// dd($cates);
   		// 排序的原生的sql语句 concat在这里是做字段链接用
   		//用原生的的sql语句查询出来数据是数组 分页时不可用 要用对象
   		// $cares = DB::select * ,concat(path,',',id) as psths from cates order by path
    	// $cates = DB::table('cate')
    	// 	->select(DB::raw('*,concat(path,",",id) as paths'))
    	// 	->orderBy('paths')
    	// 	->get();

    	//获取分页条数
        $num = $request->input('num',10);

    	//在laravel中给的where条件 传了一个闭包$query代表当前数据库对象
        $cates = DB::table('cate')
        	->select(DB::raw('*,concat(path,",",id) as paths'))
        	->orderBy('paths')
        	->where(function($query) use($request){
            //判断是否有where条件
            if ($request->input('keywords')) {
                $query->where('cname','like','%'.$request->input('keywords').'%');        
            }
        })->paginate($num);
        // dd($cates);

 	   	/*
		 	要页面显示的有层级
			男装
			|----上衣
		 	|----|----半袖
     	*/
		//遍历
		foreach ($cates as $k => $v) {
			//获取path路径的长度 
			$arr = explode(',',$v->path);
			//1为顶级类不用加|---- 2个长度为二级类加|---- 3个长度为三级类加两个|----
			$len = count($arr)-1;
			//给name加|----  所有改的是name的值$cates[$k]->name = ....
			$cates[$k]->cname = str_repeat('|----', $len).$v->cname ;
		}
		// dd($cates);

        //解析模板
   		return view('admin.cate.index',['cates'=>$cates],['request'=>$request->all()]);
        
    }


    //删除分类操作
    public function getDelete(Request $request)
    {
    	//ID
    	$id = $request->input('id');
    	//查询当前下的类是否有子类
    	$res = DB::table('cate')->where('pid',$id)->count();
    	// dd($res);
    	//有子类直接返回
    	if($res > 0){
    		return back()->with('error','该类下有子类不可删除');
    	}

    	//执行删除
    	$res = DB::table('cate')->where('id',$id)->delete();

	  	// 判断
        if($res)
        {
            return redirect('/admin/cate/index')->with('success','删除成功');
        }else
        {
            return back()->with('error','删除失败');
        }
    }


    //根据pid获取pid下的所有子类
    public static function getCatesBy($pid)
    {
    	//获取pid下面的所有子类
    	$res = DB::table('cate')->where('pid',$pid)->get();
    	// dd($res);
    	$data = [];
    	//遍历
    	foreach($res as $k => $v){
    		$v->sub = self::getCatesBy($v->id);
    		$data[] = $v;
    	}
    	//返回
    	return $data;

    }

    //优化递归
    //查询所有的分类数据
    public static function getAllCates()
    {
    	return DB::table('cate')->get();
    }

    //根据pid获取pid下的所有子类
    public static function getCatesByArr($cates,$pid)
    {

    	$data = [];
    	//遍历
    	foreach($cates as $k => $v){
    		if($v->pid == $pid){
				$v->sub = self::getCatesByArr($cates,$v->id);
				$data[] = $v;
			}
    	}
    	//返回
    	return $data;

    }

    //修改页面
    public function getEdit(Request $request)
    { 
        //获取要修改的ID
        $id = $request->input('id');
        // dd($id);
        //通过id 查询
        $cates = DB::table('cate')->where('id',$id)->first();
        //显示模板 分配变量
        return view('admin.cate.edit',['cates'=>$cates]);
    }


    //修改
    public function postDoedit(Request $request)
    {
        $this->validate($request, [
          'cname' => 'required',
        ],[
          'cname.required'=>'商品类名不能为空',
        ]);

        //提取数据
        $data = $request->only('cname');
        $id = $request->input('id');
        // dd($data);
        //查询当前下的类是否有子类
        $res = DB::table('cate')->where('pid',$id)->count();
        // dd($res);
        //有子类直接返回
        if($res > 0){
           return redirect('/admin/cate/index')->with('error','该类下有子类不可修改');
        }

        //执行修改
        $ress = DB::table('cate')->where('id',$id)->update($data);
        // 判断
        if($ress)
        {
            return redirect('/admin/cate/index')->with('success','修改成功');
        }else
        {
            return back()->with('error','修改失败');
        }

    }

    public function getUpdate(Request $request)
    {
    	$id = $request->input('id');
    	$data = $request->only('cname');
        //执行数据修改
        $res = DB::table('cate')->where('id',$id)->update($data);
        //判断返回
        if($res > 0){
            echo 1;
        }else{
            echo 0;
        }
    }

}
